<?php
namespace app\api\controller\v2;
session_start();

use think\Controller;
use think\Request;
use think\Db;
use app\api\controller\Send;
use app\api\controller\v1\Token;
use app\api\controller\v1\ali_Sms;
use think\Cache;
use JPush\Client as JPush;

/**
 * v2 Android版本 注册登录
 * Class UserRegister
 * @package app\api\controller\v2
 */
class UserRegister{
	use Send;

	public function validate_user_name($user_name){
		$result = Db::query("select * from user_info where user_name = '$user_name'");
		if (empty($result)) {
			return $this->returnmsg(200,"恭喜,用户名可以使用!");
		}else{
			return $this->returnmsg(401,"用户名已经被使用,请换一个昵称吧!");
		}
	}

	public function validate_phone($mobilephone){
		$result = Db::query("select * from ym_user where mobilephone = '$mobilephone'");
		if (empty($result)) {
			return $this->returnmsg(200,"恭喜,手机号可以使用!");
		}else{
			return $this->returnmsg(401,"手机号已经被使用!");
		}
	}

	//注册
	public function register($password,$confirm_password,$mobilephone){
		$exist = false;
        $cofirm = false;
        $psw_length = false;
        
		//$data = ['foo' => 'bar', 'bar' => 'foo'];
		// Db::table('think_user')->insert($data);
        // return $this->returnmsg(401,'username is not bind');
        // 
      	//if(!empty($code)){
      	//	$ali = new Ali;
        //	$random = $ali->checkValidPhone($mobilephone);
		//	$ali->sendSMS($mobilephone);
      	//}
        // $arr = array($username,$password,$confirm_password,$mobilephone,$code);
        // return $this->returnmsg(200,'注册成功,用户已经创建了，快去登入吧！',$arr);
		if (!empty($mobilephone) && !empty($password)) {
           

        	// $result = Db::query("select mobilephone from ym_user where mobilephone = '$mobilephone' ");
        	$result = Db::query("select * from ym_user where mobilephone = '$mobilephone' ");
       		if(!empty($result)){
       			 $exist = true;
                    // $register_result = array("register_result"=>false,"error_code"=>0,"reason"=>"user name exist");
                    // $json = json($register_result);
                 return $this->returnmsg(401,'用户已存在');

       		}else if($password != $confirm_password) {
                    //注册失败，密码不一致;
                    $cofirm = true;
                    return $this->returnmsg(402,'两次输入密码不一致');

            }else if(strlen($password) < 8 || strlen($password) >16 ) {
                    
                    //注册失败，密码不规范，长度应在8~16位;
                    $psw_length = true;
                    return $this->returnmsg(403,'密码应在8到16位之间');

			}else if(!$exist && !$cofirm && !$psw_length){
				
                // $data = ['mobilephone' => '$mobilephone','password' => '$password','reg_date' => 'now()'];
                // Db::table('ym_user')->insert($data);
                // 我觉得应该采用变量赋值判断插入是否成功
	        	//$a = new Ali;
	        	//$random = $a::random;
				// echo $_SESSION['random'];
	       		// $time = time();
	       		
	       		// $timediff = strtotime($time) - strtotime($_SESSION['time']);$code == $_SESSION['random'] &&
	       		// $timediff = $time - $_SESSION['time'];
          //   	if ($timediff < 300 && $mobilephone == $_SESSION['mobilephone']){
        
	                Db::query("insert into ym_user (id,password,mobilephone,reg_date,last_login_time) values(null,md5('$password'),'$mobilephone',now(),now())");
	                $id = Db::table('ym_user')->field('id')->where('mobilephone',$mobilephone)->select();
	                $user_id = $id[0]['id'];
	                Db::query("insert into ym_pet_food values(null,'$user_id',default)");


                    $new_token = Token::buildAccessToken($lenght = 32);
                    DB::name("user_info")->insert(['user_name' => "云喵人".rand(0,2046),'user_id']);
                    DB::query("update ym_user set access_token = '$new_token',reg_date = now() where mobilephone = '$mobilephone'");

	                return $this->returnmsg(200,'注册成功,用户已经创建了，快去登入吧！');
	            // }else{
	            // 	return $this->returnmsg(404,'验证码错误或超时或者手机号不正确');
	            // }
	        }
    	else{
                 //注册失败，数据库插入错误        
                 return $this->returnmsg(500,'Fail,Error for insert');
	            }
	        }	
	}

	//注册号
	public function get_RegistrationId($user_id,$registration_id){
		$result = Db::query("select *from ym_device_no where user_id = '$user_id'");
		if (!empty($result)) {
			
			if ($result[0]['registration_id'] != $registration_id) {
				$this->push($user_id,$result[0]['registration_id'],'你的帐号已在别的设备登入');
				$this->custom_message($user_id,$result[0]['registration_id'],'yunmiao');
				Db::query("update ym_device_no set registration_id = '$registration_id' where user_id = '$user_id'");
			}
		}else{
			$data = ['user_id'=>$user_id,'registration_id'=>$registration_id];
			Db::table("ym_device_no")->insert($data);
		}
	}

	//推送全部
	public function push($user_id,$registration_id,$message){
		$appkey = 'a3d1bad973276db7cee3f40a';
		$master_secret = 'ac5c6c6b1101643082c88913';
		$client = new JPush($appkey,$master_secret);
		// $push = $client->push()->setPlatform('all')->addAllAudience('35')->setNotificationAlert('您的帐号在别的设备登入!!');
		$push = $client->push();
		$push->setPlatform('all');
		//别名
		$push->addAlias($user_id);
		//设备号
		$push->addRegistrationId($registration_id);
		// $push->iosNotification();
		$push->iosNotification($message, [
			  'sound' => 'sound.cat',
			  'badge' => '+1',
			  'extras' => [
		       'logout' => '1'
		      ]
		]);
		$push->options(array(
		      "apns_production" => true  //true表示发送到生产环境(默认值)，false为开发环境
		    ));
		
		    $response = $push->send(); // 执行推送
		
	}

	// 发送自定义消息
	public function custom_message($user_id,$registration_id,$message){
		$appkey = '42fe34c91990795da0af8316';
		$master_secret = '5d3905677a1c98b48323dc7e';
		$client = new JPush($appkey,$master_secret);
		$payload = $client->push()
		    ->setPlatform('all')
		    ->addAlias($user_id)
		    //设备号
			->addRegistrationId($registration_id)
		    ->message($message, [
		      'title' => 'Tix',
		      'content_type' => 'text',
		      'extras' => [
		       'logout' => '1'
		      ]
		    ])
		    ->options(array(
		      "apns_production" => true  //true表示发送到生产环境(默认值)，false为开发环境
		    ));

		    
		    $response = $payload->send(); // 执行推送
		
	}




	//登入
	public function login($mobilephone,$password){
	    //检查用户是否已被注销
//        $is_cancel = $this->check_cancel($mobilephone);
//        if($is_cancel['status'])
//        {
//            return $this->returnmsg(405,'该账号已注销');
//        }
		$res = Db::query("select * from ym_user where mobilephone = '$mobilephone'");
		//检查用户是否已经注册
		if (!empty($res)) {
		    //检查用户手机号码和密码是否为空
			if (!empty($mobilephone) && !empty($password)) {
				$v = $this->check_login($mobilephone);
				//检查是否在登陆中
				if ($v == false) {
					Db::query("update ym_user set login_status = 1 where mobilephone = '$mobilephone'");
					$login_status = 0;
					$result = Db::query("select * from ym_user where mobilephone = '$mobilephone' ");
					foreach ($result as $rows) {}
					while ($rows){
						//检查手机密码是否正确
						if ($mobilephone == $rows['mobilephone'] && md5($password) == $rows['password']) {
						    //设置accesstoken
							if (is_null($rows['access_token'])){
								$access_token = Token::buildAccessToken($lenght = 32);
								Db::query("update ym_user set access_token = '$access_token' where mobilephone = '$mobilephone'");
								//验证是否第一次登录
								$a = $this->handsel_emp_and_food($rows['id']);
								$arr = array('code'=>200,'access_token'=>$access_token,'login_status'=>$login_status,'user_id'=>$rows['id'],'continue_day'=>$a['continue_day'],'pet_food'=>$a['pet_food']);

                                return $this->returnmsg(200, '登录成功', $arr);
								
							}
							else{
								$time = date("Y-m-d H:i:s",time());
								$checkclient = Db::table('ym_user')->field('reg_date')->where('mobilephone',$mobilephone)->find();
								 $timediff = strtotime($time) - strtotime($checkclient['reg_date']);
								 $time_h = $timediff / 3600;
								 if(720 <= $time_h){	
								 	
								 	$new_token = Token::buildAccessToken($lenght = 32);
									Db::query("update ym_user set access_token = '$new_token',reg_date = now() where mobilephone = '$mobilephone'");
									$a = $this->handsel_emp_and_food($rows['id']);
									$arr = array('code'=>200,'access_token'=>$new_token,'login_status'=>$login_status,'user_id'=>$rows['id'],'continue_day'=>$a['continue_day'],'pet_food'=>$a['pet_food']);

                                     return $this->returnmsg(200, '登录成功', $arr);
								 }	
							}
							$a = $this->handsel_emp_and_food($rows['id']);
							$arr = array('code'=>200,'access_token'=>$rows['access_token'],'login_status'=>$login_status,'user_id'=>$rows['id'],'continue_day'=>$a['continue_day'],'pet_food'=>$a['pet_food']);

                            return $this->returnmsg(200, '登录成功', $arr);
							
							}else{
								return $this->returnmsg(401,'手机号或者密码错误');
							}
						}
				}
				else{
					$login_status = 1;
					$result = Db::query("select * from ym_user where mobilephone = '$mobilephone' ");
					foreach ($result as $rows) {}
					while ($rows){
						if ($mobilephone == $rows['mobilephone'] && md5($password) == $rows['password']) {
							if (is_null($rows['access_token'])){
								$access_token = Token::buildAccessToken($lenght = 32);
								Db::query("update ym_user set access_token = '$access_token' where mobilephone = '$mobilephone'");
								$a = $this->handsel_emp_and_food($rows['id']);

								$arr = array('code'=>200,'access_token'=>$access_token,'login_status'=>$login_status,'user_id'=>$rows['id'],'continue_day'=>$a['continue_day'],'pet_food'=>$a['pet_food']);

                                return $this->returnmsg(200, '登录成功', $arr);
								
							}else{
								$time = date("Y-m-d H:i:s",time());
								$checkclient = Db::table('ym_user')->field('reg_date')->where('mobilephone',$mobilephone)->find();
								 $timediff = strtotime($time) - strtotime($checkclient['reg_date']);
								 $time_h = $timediff / 3600;
								 if(720 <= $time_h){	
								 	// token 过期了;
								 	$new_token = Token::buildAccessToken($lenght = 32);
									Db::query("update ym_user set access_token = '$new_token',reg_date = now() where mobilephone = '$mobilephone'");
									$a = $this->handsel_emp_and_food($rows['id']);
									$arr = array('code'=>200,'access_token'=>$new_token,'login_status'=>$login_status,'user_id'=>$rows['id'],'continue_day'=>$a['continue_day'],'pet_food'=>$a['pet_food']);
									// $this->handsel_emp_and_food($rows['id']);
                                     return $this->returnmsg(200, '登录成功', $arr);
								 }	
							}
							$a = $this->handsel_emp_and_food($rows['id']);
							$arr = array('code'=>200,'access_token'=>$rows['access_token'],'login_status'=>$login_status,'user_id'=>$rows['id'],'continue_day'=>$a['continue_day'],'pet_food'=>$a['pet_food']);
							//return json($arr);
                            return $this->returnmsg(200, '登录成功', $arr);
						}else{
							return $this->returnmsg(401,'手机号或者密码错误');
						}
					}
				}
			}
		}else{
			return $this->returnmsg(400,'还没有注册哟！请先去注册吧');
		}

	}
	//送出礼金和食物
	public function handsel_emp_and_food($user_id){
		$food = Db::query("select pet_food from ym_pet_food where user_id = '$user_id'");
        if($food){
            $pet_food = $food[0]['pet_food'];
        }else{
            $pet_food = 0;
        }
		$pet = Db::query("select pet_id from ym_pet where user_id = '$user_id'");
		$login_time = date('Y-m-d');
		$length = count($pet);
		

		for ($i=0; $i < $length; $i++) { 
			$emp = Db::query("select pet_emp from ym_pet_hungry where pet_id = '".$pet[$i]['pet_id']."'");
			if(empty($emp)){
			    continue;
            }
			$pet_emp = $emp[0]['pet_emp'];
			$emp_time = Db::query("select add_emp_time from ym_pet_hungry where pet_id = '".$pet[$i]['pet_id']."'");
			$add_emp_time = $emp_time[0]['add_emp_time'];
			// echo $add_emp_time;
			if ($login_time != $add_emp_time) {
				// echo "yes";
				Db::query("update ym_pet_hungry set pet_emp = '$pet_emp'+100 where pet_id = '".$pet[$i]['pet_id']."'");
				Db::query("update ym_pet_hungry set add_emp_time = '$login_time' where pet_id = '".$pet[$i]['pet_id']."'");
			}
		}
		$a = $this->login_handsel_pet_food($user_id);
		return $a;
	}

	// 登入送宠粮
	public function login_handsel_pet_food($user_id) {

        $food = Db::query("select pet_food from ym_pet_food where user_id = '$user_id'");
        if($food){
            $pet_food = $food[0]['pet_food'];
        }else{
            $pet_food = 0;
        }
        $time = date('Y-m-d');
        $res = Db::query("select * from ym_handsel_pet_food where user_id = '$user_id'");
        if (!empty($res)) {
            
            $result = Db::query("select last_login_time from ym_handsel_pet_food where user_id = '$user_id' ");
            // $last_login_time = $result[0]['last_login_time'];
            $last_login_time = substr($result[0]['last_login_time'],0,10);
            $timediff = (strtotime($time) - strtotime($last_login_time))/86400;//天数
            // echo $timediff;
            //$time != $last_login_time &&
            if ($timediff == 1) {//日期相隔一天
            
                $day = Db::query("select continue_day from ym_handsel_pet_food where user_id = '$user_id'");
                $last_continue_day = $day[0]['continue_day'];
                Db::query("update ym_handsel_pet_food set last_login_time = '$time',continue_day = '$last_continue_day' + 1 where user_id = '$user_id'");
                
                $day_now = Db::query("select continue_day from ym_handsel_pet_food where user_id = '$user_id'");
                $continue_day = $day_now[0]['continue_day'];
                // echo $continue_day;
                switch ($continue_day) {
                    case 7:
                        // echo "7";                   
                        Db::query("update ym_pet_food set pet_food = '$pet_food'+50 where user_id = '$user_id'");
                        Db::query("update ym_handsel_pet_food set last_login_time = '$time' where user_id = '$user_id'");
                        $arr = ['continue_day'=>$continue_day,'pet_food'=>50];
                        return $arr;
                        // return $this->returnmsg(200,'连续登录七天，送你50克宠粮哦');
                        break;
                    case 15:
                        // echo "15";
                        Db::query("update ym_pet_food set pet_food = '$pet_food'+150 where user_id = '$user_id'");
                        Db::query("update ym_handsel_pet_food set last_login_time = '$time' where user_id = '$user_id'");
                        $arr = ['continue_day'=>$continue_day,'pet_food'=>150];
                        return $arr;
                        // return $this->returnmsg(200,'连续登录15天，送你150克宠粮哦');
                        break;
                    case 30:
                        // echo "30";
                        Db::query("update ym_pet_food set pet_food = '$pet_food'+300 where user_id = '$user_id'");
                        Db::query("update ym_handsel_pet_food set continue_day = 0 where user_id = '$user_id'");
                        Db::query("update ym_handsel_pet_food set last_login_time = '$time' where user_id = '$user_id'");
                        $arr = ['continue_day'=>$continue_day,'pet_food'=>300];
                        return $arr;
                        // return $this->returnmsg(200,'连续登录30天，送你300克宠粮哦');
                        break;
                    default:
                        Db::query("update ym_pet_food set pet_food = '$pet_food'+10 where user_id = '$user_id'");
                        Db::query("update ym_handsel_pet_food set last_login_time = '$time' where user_id = '$user_id'");
                        $arr = ['continue_day'=>$continue_day,'pet_food'=>10];
                        return $arr;
                        // return $this->returnmsg(200,'登录成功，送你10克宠粮哦');
                        break;
                    }
                }elseif ($timediff > 1) {//日期相隔大于1天
                	Db::query("update ym_handsel_pet_food set continue_day = 1 where user_id = '$user_id'");
                	Db::query("update ym_pet_food set pet_food = '$pet_food'+10 where user_id = '$user_id'");
                	Db::query("update ym_handsel_pet_food set last_login_time = '$time' where user_id = '$user_id'");
                	$arr = ['continue_day'=>1,'pet_food'=>10];
                	return $arr;
                }else{//当天
                	$arr = ['continue_day'=>0,'pet_food'=>'0'];
                	return $arr;
                }
                
            }else{
                Db::query("update ym_pet_food set pet_food = '$pet_food'+10 where user_id = '$user_id'");
                Db::query("insert into ym_handsel_pet_food values(null,'$user_id',now(),default)");
                // return $this->returnmsg(200,'第一次登入成功');
            }
         }

    //更新最后一次登入时间
    public function update_last_login_time($user_id){
    	$time = date('Y-m-d H:i:s');
    	Db::query("update ym_user set last_login_time = '$time' where id = '$user_id'");
    }

	//验证token是否有效
	public function validate_token($user_id,$access_token){

		$result = Db::query("select access_token from ym_user where id = '$user_id'");
		
		if(!empty($result[0]['access_token'])){
			$time = date("Y-m-d H:i:s",time());
			$checkclient = Db::table('ym_user')->field('reg_date,last_login_time')->where('id',$user_id)->find();
			$timediff = strtotime($time) - strtotime($checkclient['reg_date']);
			$last_login_time = strtotime($time) - strtotime($checkclient['last_login_time']);
			$last_login_time_h = $last_login_time/3600;

			$time_h = $timediff / 3600;

			$this->update_last_login_time($user_id);
			if (720 <= $last_login_time_h) {
				
				$arr = array('code' => 400);
				return json($arr);
										
			}else{
				
				
				$a = $this->handsel_emp_and_food($user_id);
				$arr = array('code' => 200,'continue_day'=>$a['continue_day'],'pet_food'=>$a['pet_food']);
				return json($arr);
			}
		}else{
			$arr = array('code' => 404);
			return json($arr);
		}
	}


	public function logout($mobilephone){
		Db::query("update ym_user set login_status = 0 where mobilephone = '$mobilephone'");
		$res = Db::query("select login_status from ym_user where mobilephone = '$mobilephone'");
		$login_status = $res[0]['login_status'];
		if ($login_status == 0) {
			return $this->returnmsg(200,'登出成功','login_status: '.$login_status);
		}else{
			return $this->returnmsg(500,'登出失败','login_status: '.$login_status);
		}
	}

	//医生端登出
    public function doctor_logout($mobilephone){
        Db::query("update doctor_user set login_status = 0 where mobilephone = '$mobilephone'");
        $res = Db::query("select login_status from doctor_user where mobilephone = '$mobilephone'");
        $login_status = $res[0]['login_status'];
        if ($login_status == 0) {
            return $this->returnmsg(200,'登出成功','login_status: '.$login_status);
        }else{
            return $this->returnmsg(500,'登出失败','login_status: '.$login_status);
        }
    }

	public function check_login($mobilephone){
		$status = Db::query("select login_status from ym_user where mobilephone = '$mobilephone'");
		$login_status = $status[0]['login_status'];
		if ($login_status == 0) {
			return false;
		}else{
			return true;
		}
	}

	public function forget_psw($password,$confirm_password,$mobilephone){

		$arr = Db::query("select id from ym_user where mobilephone = '$mobilephone'");
		$id = $arr[0]['id'];
		if ($password != $confirm_password ) {
			return $this->returnmsg(401,"密码修改失败，两次输入密码不一致");
			
			}else if(strlen($password) < 8 || strlen($password) >16){
				return $this->returnmsg(402,"密码修改失败，密码长度应在8到16位之间");
			}
		else{
			Db::query("update ym_user set password = md5('$password') where id = '$id'");
			return $this->returnmsg(200,"密码修改成功");
		}
	}

	public function validate_code($mobilephone,$code){

		$result = Db::table('ym_user')->where('mobilephone',$mobilephone)->select();
		if ($result) {
			if ($code == $_SESSION['random']) {
				return $this->returnmsg(200,'进入密码修改页');
			}else{
				return $this->returnmsg(401,'验证码错误');
			}
		}else{
			return $this->returnmsg(404,'手机号输入不正确');
		}
	}

	public function send_Code($mobilephone){
		
		$ali = new ali_Sms;
        
		$ali->sendSMS($mobilephone);
		$random = $ali->checkValidPhone($mobilephone);
		//将random存进session里;
		$_SESSION['random'] = $random;
		//将当前时间存进session里
		// $_SESSION['time'] = date('y-m-d h:i:s',time());
		$_SESSION['time'] = time();

		$_SESSION['mobilephone'] = $mobilephone;
		return $this->returnmsg(200,'code',$random);
		// echo $_SESSION['random'];
		
	}

    /**
     * 检查是否为注销账户，手机号为唯一确定
     * @param $mobilephone 手机号
     * @return array|bool|false|\PDOStatement|string|\think\Model
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
	public function check_cancel($mobilephone)
    {
        try {
            $result = DB::name("ym_cancel")->where('mobilephone', '=', $mobilephone)->find();
        }
        catch(\Exception $e) {

        }
        if(!$result)
        {
            return false;
        }
        return $result;
    }
}
